package coml.allen.api.rt;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author sesshomaru
 * @date 2020/11/14 17:53
 */
public class Producer {
    public static void main(String[] args) throws Exception{
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.1.102");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String ex = "test_return_ex";
        String exError = "bbbbbbb";
        String rk = "return.save";
        String rkError = "abc.save";

        // 添加return监听，监听不可达的消息
        channel.addReturnListener(new ReturnListener() {
            /**
             *
             * @param replyCode 响应码
             * @param replyText 响应文本
             * @param exchange  具体路由的交换机
             * @param routingKey    路由key
             * @param properties    配置
             * @param body          消息体
             * @throws IOException
             */
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                                     AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.err.println("----------- 生产端 return监听 -----------");
                System.err.println("replyCode: "+replyCode);
                System.err.println("replyText: "+replyText);
                System.err.println("exchange: "+exchange);
                System.err.println("routingKey: "+routingKey);
                System.err.println("properties: "+properties);
                System.err.println("body: "+new String(body));
            }
        });
        String msg = "测试return监听";
        // 注意这里的 mandatory 一定要设置为true，这样路由不到的消息才不会被删除 return监听才会起作用
        // 说人话就是 如果发送到了exchange但是没有符合规则的queue可以投递就会自动把这个消息删除掉不做保存 mandatory = false时
        channel.basicPublish(ex,rkError,true,null,msg.getBytes());
    }
}
